package com.tcm.pay.util;


import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * Created by xc on 2018/12/24.
 */
public class Base64Util {
    public static String encode(String s){//转码
        String res="";
        res= new BASE64Encoder().encode(s.getBytes(StandardCharsets.UTF_8));
        return  res;
    }
    public static byte[] decode(String str){//解码
        byte[] bt = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            bt = decoder.decodeBuffer( str );
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return bt;
    }
    
    /**
     * 加密文件:将文件转成base64 字符串
     * @param
     * @throws Exception
     */
    public static String encryptFile(String path) {
        InputStream in = null;
        OutputStream out = null;
        String key = "";
        try {
            File f = new File(path);
            in = new FileInputStream(f);
            out = new ByteArrayOutputStream();
            new BASE64Encoder().encodeBuffer(in, out);
            key = out.toString();
            in.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return key;
    }
    
    /**
     * 将base64字符串解码保存文件
     * @param
     * @throws Exception
     */

    public static void decoderBase64File(String base64Code,String targetPath) throws Exception {
        byte[] bytes = new BASE64Decoder().decodeBuffer(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(bytes);
        out.close();
    }
    

}
